<template>
  <div class="details-container">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="text-large font-600 mr-3"> 溯源详情 </span>
      </template>
      <template #extra>
        <div class="action-buttons">
          <el-button type="primary" @click="openEditDialog">修改基本信息</el-button>
          <el-button @click="openExportDialog">导出溯源码</el-button>
        </div>
      </template>
    </el-page-header>
    <!-- 顶部主信息卡片 -->
    <el-card class="main-info-card" v-if="details">
      <div class="main-info-flex">
        <div class="product-image">
          <el-image style="width: 250px; height: 250px; border-radius: 10px;" :src="getFullImageUrl(details.CoverImageUrl)" fit="cover"
            :preview-src-list="[getFullImageUrl(details.CoverImageUrl)]" />
        </div>
        <div class="product-info">
          <h1 class="product-name">{{ details.FoodcommoditiesName }}</h1>
          <el-row :gutter="40" class="info-grid">
            <el-col :span="12">
              <div class="info-item">
                <span class="label">生产批次:</span>
                <span class="value">{{ details.BatchNumber }}</span>
              </div>
              <div class="info-item">
                <span class="label">生产许可证号:</span>
                <span class="value">{{ details.ProductionLicense }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">保质期:</span>
                <span class="value">{{ details.ShelfLifeDays }} 天</span>
              </div>
              <div class="info-item">
                <span class="label">生产企业:</span>
                <span class="value">{{ details.Manufacturer }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="report-section">
        <h3>产品检验报告</h3>
        <div class="report-images">
          <!-- 产品检验报告图片上传，最多上传9张，上传接口为CommodityInfoWrite//api/Picture/UploadImages，需带commodityId参数，上传成功后回显图片 -->
          <el-upload :action="uploadAction" :file-list="reportFileList" list-type="picture-card" :limit="9"
            :on-success="handleReportUploadSuccess" :on-remove="handleReportRemove" :before-upload="beforeReportUpload"
            :data="{ commodityId: details?.CommodityId }" :auto-upload="true" :name="'files'" multiple accept="image/*">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </div>
      </div>
    </el-card>

    <!-- 下方tab区域 -->
    <el-card class="tab-card" v-if="details">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="养殖信息(5/5)" name="aquaculture">
          <div class="aquaculture-card">
            <div style="display: flex; align-items: center; margin-bottom: 8px;">
              <span class="section-title-blue">养殖信息</span>
              <el-button type="primary" size="small" @click="openEditAquacultureDialog"
                style="margin-left: 12px;">养殖设置</el-button>
            </div>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="品种">{{ aquacultureInfo?.Breed || '-' }}</el-descriptions-item>
              <el-descriptions-item label="来源">{{ aquacultureInfo?.Source || '-' }}</el-descriptions-item>
              <el-descriptions-item label="饲养天数">{{ aquacultureInfo?.FeedingDays || '-' }} 天</el-descriptions-item>
              <el-descriptions-item label="饲料品牌">{{ aquacultureInfo?.FeedBrand || '-' }}</el-descriptions-item>
              <el-descriptions-item label="饲养负责人">{{ aquacultureInfo?.ResponsiblePerson || '-' }}</el-descriptions-item>
              <el-descriptions-item label="出栏日期">{{ aquacultureInfo?.OutDate ? formatDateTime(aquacultureInfo.OutDate || '') : '-' }}</el-descriptions-item>
            </el-descriptions>
            <!-- 保健信息模块 -->
            <div class="healthcare-section" style="margin-top: 24px;">
              <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <span class="section-title-blue">保健信息</span>
                <el-button type="primary" size="small" @click="addHealthcareRow">新增行</el-button>
              </div>
              <el-table :data="healthcareList" style="width: 100%;">
                <el-table-column prop="Feeding_days" label="饲养天数" width="120">
                  <template #default="scope">
                    <el-input v-if="scope.row._edit" v-model="scope.row.Feeding_days" maxlength="5"
                      @input="onInputNumber(scope.row)" />
                    <span v-else>{{ scope.row.Feeding_days }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="Health_care_methods" label="保健方式" width="180">
                  <template #default="scope">
                    <el-input v-if="scope.row._edit" v-model="scope.row.Health_care_methods" maxlength="30"
                      @input="onInputText(scope.row, 'Health_care_methods')" />
                    <span v-else>{{ scope.row.Health_care_methods }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="Method" label="保健方法" width="180">
                  <template #default="scope">
                    <el-input v-if="scope.row._edit" v-model="scope.row.Method" maxlength="30"
                      @input="onInputText(scope.row, 'Method')" />
                    <span v-else>{{ scope.row.Method }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                  <template #default="scope">
                    <template v-if="scope.row._edit">
                      <el-button type="primary" size="small" @click="saveHealthcareRow">保存</el-button>
                      <el-button size="small" @click="cancelHealthcareRow(scope.row)">取消</el-button>
                    </template>
                    <template v-else>
                      <el-button type="primary" size="small" @click="editHealthcareRow(scope.row)">修改</el-button>
                      <el-button type="danger" size="small" @click="deleteHealthcareRow(scope.row)">删除</el-button>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 动检证图片上传 -->
            <div class="dynamic-inspection-section" style="margin-top: 24px;">
              <span class="section-title-blue">动检证</span>
              <el-upload :action="dynamicInspectionUploadAction" :file-list="dynamicInspectionFileList"
                list-type="picture-card" :limit="9" :on-success="handleDynamicInspectionUploadSuccess"
                :on-remove="handleDynamicInspectionRemove" :before-upload="beforeDynamicInspectionUpload"
                :data="{ AquacultureId: aquacultureInfo?.AquacultureId }" :auto-upload="true" :name="'Files'" multiple
                accept="image/*">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
            <!-- 企业信息展示 -->
            <div class="enterprise-info-container">
              <div style="display: flex; align-items: center; margin-bottom: 8px; margin-top: 24px;">
                <span class="section-title-blue">企业信息</span>
                <el-button size="small" style="margin-left: 16px;" @click="openEnterpriseDialog">设置</el-button>
              </div>
              <div class="enterprise-info-row">
                <span class="enterprise-info-label">养殖场：</span>
                <span>{{ enterpriseInfo?.Breeding_farm || '-' }}</span>
                <span class="enterprise-info-label" style="margin-left: 40px;">负责人：</span>
                <span>{{ enterpriseInfo?.Person_in_charge || '-' }}</span>
              </div>
              <div class="enterprise-info-row">
                <span class="enterprise-info-label">存栏数量：</span>
                <span>{{ enterpriseInfo?.Numberbooksstock ? enterpriseInfo.Numberbooksstock + ' 只' : '-' }}</span>
              </div>
            </div>
            <!-- 企业照片上传与回显 -->
            <div class="enterprise-photo-section">
              <div style="display: flex; align-items: center; margin-bottom: 8px; margin-top: 24px;">
                <span class="section-title-blue">企业照片</span>
              </div>
              <el-upload :action="enterprisePhotoUploadAction" :file-list="enterprisePhotoFileList"
                list-type="picture-card" :limit="9" :on-success="handleEnterprisePhotoUploadSuccess"
                :on-remove="handleEnterprisePhotoRemove" :before-upload="beforeEnterprisePhotoUpload"
                :data="{ AquacultureId: aquacultureInfo?.AquacultureId }" :auto-upload="true" :name="'Files'" multiple
                accept="image/*">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="屠宰信息(5/5)" name="slaughter">
          <div style="padding: 24px;">
            <div style="display: flex; align-items: center; margin-bottom: 16px;">
              <span style="font-size: 20px; font-weight: bold; color: #1976d2;">屠宰信息</span>
              <el-button size="small" style="margin-left: 16px;" @click="openSlaughterDialog">设置</el-button>
            </div>
            <el-divider />
            <div style="display: flex; flex-wrap: wrap; gap: 40px;">
              <div>批次：{{ slaughterInfo ? slaughterInfo.BatchNo : '-' }}</div>
              <div>到厂均重：{{ slaughterInfo ? slaughterInfo.AvgWeight + ' 公斤' : '-' }}</div>
            </div>
            <div style="display: flex; flex-wrap: wrap; gap: 40px; margin-top: 16px;">
              <div>到厂时间：{{ slaughterInfo ? formatDateTime(slaughterInfo.ArriveTime || '') : '-' }}</div>
              <div>屠宰时间：{{ slaughterInfo ? formatDateTime(slaughterInfo.SlaughterTime || '') : '-' }}</div>
            </div>
            <div style="margin-top: 32px;">
              <div style="font-size: 20px; font-weight: bold; color: #1976d2; margin-bottom: 16px;">相关资质</div>
              <template v-if="slaughterEnterpriseInfo?.SlaughterhousEenterpriseId">
                <el-upload ref="slaughterQualificationUploadRef" :action="slaughterQualificationUploadAction"
                  :file-list="slaughterQualificationFileList" list-type="picture-card" :limit="9"
                  :on-success="handleSlaughterQualificationUploadSuccess" :on-remove="handleSlaughterQualificationRemove"
                  :before-upload="beforeSlaughterQualificationUpload"
                  :data="{ SlaughterId: slaughterInfo?.SlaughterId, SlaughterhousEenterpriseId: slaughterEnterpriseInfo?.SlaughterhousEenterpriseId }"
                  :auto-upload="true" :name="'Files'" multiple accept="image/*">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  <template #file="{ file, index }">
                    <div class="custom-upload-card">
                      <img :src="getFullImageUrl(file.url)" class="custom-upload-img" />
                      <div class="custom-upload-mask">
                        <el-icon class="custom-upload-action" @click.stop="handlePreview(file)"><zoom-in /></el-icon>
                        <el-icon class="custom-upload-action" @click.stop="handleRemoveSlaughterQualificationFile(file)">
                          <delete />
                        </el-icon>
                      </div>
                      <el-button v-if="index === 0" type="primary" size="small"
                        style="width: 80%; margin: 12px auto 0 auto; display: block;">宰前检疫</el-button>
                      <el-button v-else-if="index === 1" type="primary" size="small"
                        style="width: 80%; margin: 12px auto 0 auto; display: block;">宰后质检</el-button>
                    </div>
                  </template>
                </el-upload>
              </template>
              <template v-else>
                <div style="color:#bbb;min-height:120px;display:flex;align-items:center;justify-content:center;border:1px dashed #eee;border-radius:8px;background:#fafbfc;">
                  请先设置并保存企业信息后再上传相关资质
                </div>
              </template>
            </div>
            <div style="margin-top: 32px;">
              <div style="display: flex; align-items: center; margin-bottom: 16px;">
                <span style="font-size: 20px; font-weight: bold; color: #1976d2;">企业信息</span>
                <el-button size="small" style="margin-left: 16px;" @click="openSlaughterEnterpriseDialog">设置</el-button>
              </div>
              <div style="margin-bottom: 16px;">
                <div v-if="slaughterEnterpriseInfo">
                  <div style="display: flex; gap: 40px; margin-bottom: 8px;">
                    <div>公司名称：{{ slaughterEnterpriseInfo.CompanyName }}</div>
                    <div>成立时间：{{ slaughterEnterpriseInfo.EstablishmentDate ?
                      formatDateTimeZh(slaughterEnterpriseInfo.EstablishmentDate) : '-' }}</div>
                  </div>
                  <div style="margin-bottom: 8px;">公司地址：{{ slaughterEnterpriseInfo.CompanyAddress }}</div>
                  <div>公司简介：{{ slaughterEnterpriseInfo.CompanyProfile || '-' }}</div>
                  <!-- 屠宰企业照片上传与回显 -->
                  <div style="margin-top: 32px;">
                    <div style="font-size: 20px; font-weight: bold; color: #1976d2; margin-bottom: 16px;">企业照片</div>
                    <el-upload :action="slaughterEnterprisePhotoUploadAction"
                      :file-list="slaughterEnterprisePhotoFileList" list-type="picture-card" :limit="9"
                      :on-success="handleSlaughterEnterprisePhotoUploadSuccess"
                      :on-remove="handleSlaughterEnterprisePhotoRemove"
                      :before-upload="beforeSlaughterEnterprisePhotoUpload"
                      :data="{ SlaughterhousEenterpriseId: slaughterEnterpriseInfo?.SlaughterhousEenterpriseId }"
                      :auto-upload="true" :name="'Files'" multiple accept="image/*">
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </el-upload>
                  </div>
                </div>
                <div v-else style="color: #bbb;">暂无企业信息</div>
              </div>
            </div>
          </div>
          <el-dialog v-model="slaughterDialogVisible" title="屠宰信息" width="500px">
            <el-form :model="slaughterForm" label-width="120px" ref="slaughterFormRef">
              <el-form-item label="批次" required>
                <el-input v-model="slaughterForm.BatchNo" maxlength="30" @input="onBatchNoInput($event)" />
              </el-form-item>
              <el-form-item label="到厂均重(公斤)" required>
                <el-input v-model="slaughterForm.AvgWeight" maxlength="5" @input="onAvgWeightInput($event)" />
              </el-form-item>
              <el-form-item label="到厂时间" required>
                <el-date-picker v-model="slaughterForm.ArriveTime" type="datetime" style="width: 100%;" />
              </el-form-item>
              <el-form-item label="屠宰时间" required>
                <el-date-picker v-model="slaughterForm.SlaughterTime" type="datetime" style="width: 100%;" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="slaughterDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveSlaughter">保存</el-button>
            </template>
          </el-dialog>
          <el-dialog v-model="slaughterEnterpriseDialogVisible" title="企业信息" width="600px">
            <el-form :model="slaughterEnterpriseForm" label-width="100px" ref="slaughterEnterpriseFormRef">
              <el-form-item label="公司名称" required>
                <el-input v-model="slaughterEnterpriseForm.CompanyName" maxlength="30" />
              </el-form-item>
              <el-form-item label="公司地址" required>
                <el-input v-model="slaughterEnterpriseForm.CompanyAddress" maxlength="100" />
              </el-form-item>
              <el-form-item label="成立时间" required>
                <el-date-picker v-model="slaughterEnterpriseForm.EstablishmentDate" type="date" style="width: 100%;" />
              </el-form-item>
              <el-form-item label="公司简介">
                <el-input v-model="slaughterEnterpriseForm.CompanyProfile" maxlength="500" type="textarea"
                  :autosize="{ minRows: 3, maxRows: 6 }" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="slaughterEnterpriseDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveSlaughterEnterprise">保存</el-button>
            </template>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="深加工信息(0/5)" name="deep">
          <div style="padding: 24px 0 0 0;">
            <div style="display: flex; align-items: center; margin-bottom: 16px;">
              <span class="section-title-blue">深加工信息</span>
              <el-button size="small" style="margin-left: 16px;" @click="openProcessingDialog">设置</el-button>
            </div>
            <el-divider />
            <div style="display: flex; flex-wrap: wrap; gap: 40px;">
              <div>班组：{{ processingInfo ? processingInfo.GroupName : '-' }}</div>
              <div>负责人：{{ processingInfo ? processingInfo.ResponsiblePerson : '-' }}</div>
            </div>
            <div style="margin-top: 32px;">
              <div class="section-title-blue" style="margin-bottom: 16px;">食品安全信息</div>
              <el-upload ref="processingFoodSafetyUploadRef" :action="processingFoodSafetyUploadAction"
                :file-list="processingFoodSafetyFileList" list-type="picture-card" :limit="9"
                :on-success="handleProcessingFoodSafetyUploadSuccess" :on-remove="handleProcessingFoodSafetyRemove"
                :before-upload="beforeProcessingFoodSafetyUpload" :data="{ ProcessingID: processingInfo?.ProcessingID }"
                :auto-upload="true" :name="'Files'" multiple accept="image/*">
                <el-icon>
                  <Plus />
                </el-icon>
                <template #file="{ file, index }">
                  <div class="custom-upload-card">
                    <img :src="getFullImageUrl(file.url)" class="custom-upload-img" />
                    <div class="custom-upload-mask">
                      <el-icon class="custom-upload-action" @click.stop="handlePreview(file)"><zoom-in /></el-icon>
                      <el-icon class="custom-upload-action" @click.stop="handleRemoveProcessingFoodSafetyFile(file)">
                        <delete />
                      </el-icon>
                    </div>
                    <el-button v-if="index === 0" type="primary" size="small"
                      style="width: 80%; margin: 12px auto 0 auto; display: block;">人员卫生情况</el-button>
                    <el-button v-else-if="index === 1" type="primary" size="small"
                      style="width: 80%; margin: 12px auto 0 auto; display: block;">抽检报告</el-button>
                  </div>
                </template>
              </el-upload>
            </div>
            <!-- 供应商信息展示区域 -->
            <div style="margin-top: 32px;">
              <div class="section-title-blue" style="margin-bottom: 16px;">供应商信息</div>
              <div class="supplier-block">
                <div class="supplier-title">
                  <span class="supplier-type-bar"></span>
                  <span>原料</span>
                  <el-button size="small" style="margin-left: 16px;" @click="openSupplierDialog('raw', supplyInfo, processingInfo?.ProcessingID)">
                    {{ supplyInfo?.SupplyofgoodsId ? '设置' : '添加' }}
                  </el-button>
                </div>
                <div class="supplier-batch">生产批次：{{ supplyInfo?.Raw_materials || '无' }}</div>
                <!-- 只在原料卡片下方显示相关材料图片上传与回显 -->
                <div class="supplier-images" style="margin-top: 12px;">
                  <div style="font-weight:bold;font-size:16px;margin-bottom:8px;">相关材料</div>
                  <el-upload
                    :http-request="customRawMaterialsUpload"
                    :file-list="rawMaterialsImages"
                    list-type="picture-card"
                    :limit="9"
                    :on-success="handleRawMaterialsUploadSuccess"
                    :on-remove="handleRawMaterialsRemove"
                    :before-upload="beforeRawMaterialsUpload"
                    :auto-upload="true"
                    :name="'Files'"
                    multiple
                    accept="image/*"
                  >
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file, index }">
                      <div class="custom-upload-card">
                        <img :src="getFullImageUrl(file.url)" class="custom-upload-img" />
                        <div class="custom-upload-mask">
                          <el-icon class="custom-upload-action" @click.stop="handlePreview(file)"><zoom-in /></el-icon>
                          <el-icon class="custom-upload-action" @click.stop="handleRawMaterialsRemove(file)"><delete /></el-icon>
                        </div>
                        <div v-if="index < 3" class="img-label" style="background:#409EFF;color:#fff;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          {{ ['检验报告','进厂验收记录','供应商资质'][index] }}
                        </div>
                        <div v-else class="img-label" style="background:#eee;color:#666;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          相关材料
                        </div>
                      </div>
                    </template>
                  </el-upload>
                </div>
              </div>
              <!-- 其他类型（辅料、添加剂、包材）卡片不再显示相关材料图片上传区，仅保留生产批次等信息 -->
              <div class="supplier-block">
                <div class="supplier-title">
                  <span class="supplier-type-bar"></span>
                  <span>辅料</span>
                  <el-button size="small" style="margin-left: 16px;" @click="openSupplierDialog('aux', supplyInfo, processingInfo?.ProcessingID)">设置</el-button>
                </div>
                <div class="supplier-batch">生产批次：{{ supplyInfo?.Auxiliary_materials || '无' }}</div>
                <!-- 辅料相关材料图片上传与回显 -->
                <div class="supplier-images" style="margin-top: 12px;">
                  <div style="font-weight:bold;font-size:16px;margin-bottom:8px;">相关材料</div>
                  <el-upload
                    :http-request="customAuxMaterialsUpload"
                    :file-list="auxMaterialsImages"
                    list-type="picture-card"
                    :limit="9"
                    :on-success="handleAuxMaterialsUploadSuccess"
                    :on-remove="handleAuxMaterialsRemove"
                    :before-upload="beforeAuxMaterialsUpload"
                    :auto-upload="true"
                    :name="'Files'"
                    multiple
                    accept="image/*"
                  >
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file, index }">
                      <div class="custom-upload-card">
                        <img :src="getFullImageUrl(file.url)" class="custom-upload-img" />
                        <div class="custom-upload-mask">
                          <el-icon class="custom-upload-action" @click.stop="handlePreview(file)"><zoom-in /></el-icon>
                          <el-icon class="custom-upload-action" @click.stop="handleAuxMaterialsRemove(file)"><delete /></el-icon>
                        </div>
                        <div v-if="index < 3" class="img-label" style="background:#409EFF;color:#fff;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          {{ ['检验报告','进厂验收记录','供应商资质'][index] }}
                        </div>
                        <div v-else class="img-label" style="background:#eee;color:#666;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          相关材料
                        </div>
                      </div>
                    </template>
                  </el-upload>
                </div>
              </div>
              <div class="supplier-block">
                <div class="supplier-title">
                  <span class="supplier-type-bar"></span>
                  <span>添加剂</span>
                  <el-button size="small" style="margin-left: 16px;" @click="openSupplierDialog('add', supplyInfo, processingInfo?.ProcessingID)">设置</el-button>
                </div>
                <div class="supplier-batch">生产批次：{{ supplyInfo?.Additive || '无' }}</div>
                <!-- 添加剂相关材料图片上传与回显 -->
                <div class="supplier-images" style="margin-top: 12px;">
                  <div style="font-weight:bold;font-size:16px;margin-bottom:8px;">相关材料</div>
                  <el-upload
                    :http-request="customAddMaterialsUpload"
                    :file-list="addMaterialsImages"
                    list-type="picture-card"
                    :limit="9"
                    :on-success="handleAddMaterialsUploadSuccess"
                    :on-remove="handleAddMaterialsRemove"
                    :before-upload="beforeAddMaterialsUpload"
                    :auto-upload="true"
                    :name="'Files'"
                    multiple
                    accept="image/*"
                  >
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file, index }">
                      <div class="custom-upload-card">
                        <img :src="getFullImageUrl(file.url)" class="custom-upload-img" />
                        <div class="custom-upload-mask">
                          <el-icon class="custom-upload-action" @click.stop="handlePreview(file)"><zoom-in /></el-icon>
                          <el-icon class="custom-upload-action" @click.stop="handleAddMaterialsRemove(file)"><delete /></el-icon>
                        </div>
                        <div v-if="index < 3" class="img-label" style="background:#409EFF;color:#fff;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          {{ ['检验报告','进厂验收记录','供应商资质'][index] }}
                        </div>
                        <div v-else class="img-label" style="background:#eee;color:#666;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          相关材料
                        </div>
                      </div>
                    </template>
                  </el-upload>
                </div>
              </div>
              <div class="supplier-block">
                <div class="supplier-title">
                  <span class="supplier-type-bar"></span>
                  <span>包材</span>
                  <el-button size="small" style="margin-left: 16px;" @click="openSupplierDialog('pack', supplyInfo, processingInfo?.ProcessingID)">设置</el-button>
                </div>
                <div class="supplier-batch">生产批次：{{ supplyInfo?.Packaging_materials || '无' }}</div>
                <!-- 包材相关材料图片上传与回显 -->
                <div class="supplier-images" style="margin-top: 12px;">
                  <div style="font-weight:bold;font-size:16px;margin-bottom:8px;">相关材料</div>
                  <el-upload
                    :http-request="customPackMaterialsUpload"
                    :file-list="packMaterialsImages"
                    list-type="picture-card"
                    :limit="9"
                    :on-success="handlePackMaterialsUploadSuccess"
                    :on-remove="handlePackMaterialsRemove"
                    :before-upload="beforePackMaterialsUpload"
                    :auto-upload="true"
                    :name="'Files'"
                    multiple
                    accept="image/*"
                  >
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file, index }">
                      <div class="custom-upload-card">
                        <img :src="getFullImageUrl(file.url)" class="custom-upload-img" />
                        <div class="custom-upload-mask">
                          <el-icon class="custom-upload-action" @click.stop="handlePreview(file)"><zoom-in /></el-icon>
                          <el-icon class="custom-upload-action" @click.stop="handlePackMaterialsRemove(file)"><delete /></el-icon>
                        </div>
                        <div v-if="index < 3" class="img-label" style="background:#409EFF;color:#fff;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          {{ ['检验报告','进厂验收记录','供应商资质'][index] }}
                        </div>
                        <div v-else class="img-label" style="background:#eee;color:#666;text-align:center;line-height:28px;border-radius:4px;margin-top:4px;">
                          相关材料
                        </div>
                      </div>
                    </template>
                  </el-upload>
                </div>
              </div>
            </div>
            <!-- 供应商信息展示区域下方插入企业信息展示区 -->
            <div style="margin-top: 32px; border-radius: 12px; padding: 24px 24px 16px 24px;">
              <div style="display: flex; align-items: center; margin-bottom: 16px;">
                <span style="font-weight: bold; color: #1976d2; font-size: 22px;">企业信息</span>
                <el-button size="medium" style="margin-left: 16px; font-size: 16px;" @click="openProcessingEnterpriseDialog">设置</el-button>
              </div>
              <el-divider style="margin: 8px 0 24px 0;" />
              <div>
                <div v-if="processingEnterpriseInfo" style="display: flex; justify-content: flex-start; align-items: center; gap: 80px; min-height: 40px;">
                  <span style="font-size: 18px; color: #333;">公司名称：<span style="font-weight: 500;">{{ processingEnterpriseInfo.Company_Name }}</span></span>
                  <span style="font-size: 18px; color: #333;">生产许可证号：<span style="font-weight: 500;">{{ processingEnterpriseInfo.Production_license }}</span></span>
                </div>
                <div v-else style="color: #bbb; font-size: 16px; min-height: 40px;">暂无企业信息</div>
              </div>
              <!-- 企业照片上传与回显 -->
              <div v-if="processingEnterpriseInfo && processingEnterpriseInfo.Processing_enterpriseInfoId" style="margin-top: 16px;">
                <div class="section-title-blue" style="margin-bottom: 8px;">企业照片</div>
                <el-upload
                  :action="processingEnterprisePhotoUploadAction"
                  :file-list="processingEnterprisePhotoFileList"
                  list-type="picture-card"
                  :limit="9"
                  :on-success="handleProcessingEnterprisePhotoUploadSuccess"
                  :on-remove="handleProcessingEnterprisePhotoRemove"
                  :before-upload="beforeProcessingEnterprisePhotoUpload"
                  :data="{ Processing_enterpriseInfoId: processingEnterpriseInfo.Processing_enterpriseInfoId }"
                  :auto-upload="true"
                  :name="'Files'"
                  multiple
                  accept="image/*"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </div>
            </div>
          </div>
          <el-dialog v-model="processingDialogVisible" title="企业信息" width="500px">
            <el-form :model="processingForm" label-width="120px" ref="processingFormRef">
              <el-form-item label="班组" required>
                <el-input v-model="processingForm.GroupName" maxlength="30" />
              </el-form-item>
              <el-form-item label="负责人" required>
                <el-input v-model="processingForm.ResponsiblePerson" maxlength="30" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="processingDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveProcessing">保存</el-button>
            </template>
          </el-dialog>
          <!-- 在企业信息区下方插入弹窗表单模板 -->
          <el-dialog v-model="processingEnterpriseDialogVisible" title="企业信息" width="400px">
            <el-form :model="processingEnterpriseForm" label-width="120px">
              <el-form-item label="公司名称" required>
                <el-input v-model="processingEnterpriseForm.Company_Name" />
              </el-form-item>
              <el-form-item label="生产许可证号" required>
                <el-input v-model="processingEnterpriseForm.Production_license" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="processingEnterpriseDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveProcessingEnterprise">保存</el-button>
            </template>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-skeleton :rows="10" animated v-else />
    <!-- 修改基本信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改基本信息" width="500px">
      <el-form :model="editForm" label-width="120px" ref="editFormRef">
        <el-form-item label="商品ID" prop="CommodityId" v-if="false">
          <el-input v-model="editForm.CommodityId" />
        </el-form-item>
        <el-form-item label="商品名称ID" prop="FoodcommoditiesId" v-if="false">
          <el-input v-model="editForm.FoodcommoditiesId" />
        </el-form-item>
        <el-form-item label="生产批次" prop="BatchNumber">
          <el-input v-model="editForm.BatchNumber" />
        </el-form-item>
        <el-form-item label="保质期(天)" prop="ShelfLifeDays">
          <el-input-number v-model="editForm.ShelfLifeDays" :min="1" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="ProductionLicense">
          <el-input v-model="editForm.ProductionLicense" />
        </el-form-item>
        <el-form-item label="生产企业" prop="Manufacturer">
          <el-input v-model="editForm.Manufacturer" />
        </el-form-item>
        <!-- 其余字段隐藏但editForm要有 -->
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave">保存</el-button>
      </template>
    </el-dialog>
    <!-- 导出溯源码弹窗 -->
    <el-dialog v-model="exportDialogVisible" title="导出设置" width="400px">
      <el-form :model="exportForm">
        <el-form-item label="导出数量">
          <el-input-number v-model="exportForm.ExportCount" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="二维码尺寸">
          <el-input-number v-model="exportForm.QrCodeSize" :min="100" :max="1000" />
        </el-form-item>
        <el-form-item label="格式">
          <el-select v-model="exportForm.Format">
            <el-option label="PNG" value="PNG" />
            <el-option label="JPG" value="JPG" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
      </template>
    </el-dialog>
    <!-- 编辑养殖信息弹窗 -->
    <el-dialog v-model="editAquacultureDialogVisible" title="编辑养殖信息" width="500px">
      <el-form :model="editAquacultureForm" label-width="110px">
        <el-form-item label="品种" prop="Breed">
          <el-input v-model="editAquacultureForm.Breed" />
        </el-form-item>
        <el-form-item label="来源" prop="Source">
          <el-input v-model="editAquacultureForm.Source" />
        </el-form-item>
        <el-form-item label="饲养天数" prop="FeedingDays">
          <el-input-number v-model="editAquacultureForm.FeedingDays" :min="0" />
        </el-form-item>
        <el-form-item label="饲料品牌" prop="FeedBrand">
          <el-input v-model="editAquacultureForm.FeedBrand" />
        </el-form-item>
        <el-form-item label="饲养负责人" prop="ResponsiblePerson">
          <el-input v-model="editAquacultureForm.ResponsiblePerson" />
        </el-form-item>
        <el-form-item label="出栏日期">
          <el-date-picker v-model="editAquacultureForm.OutDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"
            style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editAquacultureDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAquaculture">保存</el-button>
      </template>
    </el-dialog>
    <!-- 企业信息弹窗 -->
    <el-dialog v-model="enterpriseDialogVisible" title="企业信息设置" width="500px">
      <el-form :model="enterpriseForm" label-width="110px">
        <el-form-item label="养殖场" prop="Breeding_farm">
          <el-input v-model="enterpriseForm.Breeding_farm" />
        </el-form-item>
        <el-form-item label="负责人" prop="Person_in_charge">
          <el-input v-model="enterpriseForm.Person_in_charge" />
        </el-form-item>
        <el-form-item label="存栏数量" prop="Numberbooksstock">
          <el-input-number v-model="enterpriseForm.Numberbooksstock" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="enterpriseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEnterpriseSave">保存</el-button>
      </template>
    </el-dialog>
    <!-- 供应商信息弹框 -->
    <el-dialog v-model="supplierDialogVisible" :title="'供应商信息-' + (supplierDialogType==='raw'?'原料':supplierDialogType==='aux'?'辅料':supplierDialogType==='add'?'添加剂':'包材')" width="500px">
      <el-form :model="supplierForm" label-width="120px">
        <el-form-item label="生产批次" required v-if="supplierDialogType==='raw'">
          <el-input v-model="supplierForm.Raw_materials" maxlength="30" :disabled="!isAddRaw && supplierDialogType==='raw' && !supplierForm.SupplyofgoodsId" />
        </el-form-item>
        <el-form-item label="生产批次" required v-if="supplierDialogType==='aux'">
          <el-input v-model="supplierForm.Auxiliary_materials" maxlength="30" />
        </el-form-item>
        <el-form-item label="生产批次" required v-if="supplierDialogType==='add'">
          <el-input v-model="supplierForm.Additive" maxlength="30" />
        </el-form-item>
        <el-form-item label="生产批次" required v-if="supplierDialogType==='pack'">
          <el-input v-model="supplierForm.Packaging_materials" maxlength="30" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveSupplier">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CommodityInfoRead, CommodityInfoWrite } from '@/utils/axionrequest';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const details = ref<any>(null);
const slaughterInfo = ref<any>(null)

interface AquacultureInfo {
  AquacultureId: number;
  Breed: string;
  FoodcommoditiesId: number;
  Source: string;
  FeedingDays: number;
  FeedBrand: string;
  ResponsiblePerson: string;
  OutDate: string;
  CreateTime: string;
  UpdateTime: string;
  IsDelete: boolean;
}
const aquacultureInfo = ref<AquacultureInfo | null>(null)

const enterpriseInfo = ref<any>(null)

const fetchDetails = async () => {
  const commodityId = route.params.id;
  if (!commodityId) {
    ElMessage.error('无法获取商品ID');
    return;
  }

  try {
    const response = await CommodityInfoRead.get('/api/Commodity/SearchDetails', {
      params: { CommodityId: commodityId }
    });
    if (response.data.code === 200 && response.data.data.length > 0) {
      details.value = response.data.data[0];
      // 解析历史图片，回显到el-upload
      if (details.value.Inspectionreport) {
        reportFileList.value = details.value.Inspectionreport
          .split(',')
          .filter((url: string) => Boolean(url))
          .map((url: string, idx: number) => ({
            name: `图片${idx + 1}`,
            url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
            status: 'done'
          }))
      } else {
        reportFileList.value = []
      }
      // 加载养殖信息
      fetchAquacultureInfo(details.value.FoodcommoditiesId)
    } else {
      ElMessage.error(response.data.msg || '未能加载商品详情');
    }
  } catch (error) {
    ElMessage.error('请求商品详情失败');
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  fetchDetails();
});

// 修改基本信息弹窗相关
const editDialogVisible = ref(false)
const editForm = reactive({
  CommodityId: null,
  FoodcommoditiesId: null,
  BatchNumber: '',
  ShelfLifeDays: 0,
  ProductionLicense: '',
  Manufacturer: '',
  CoverImageUrl: '',
  Perfect: '',
  Founder: '',
  Modifier: '',
  CreateTime: '',
  IsDelete: false,
  Inspectionreport: ''
})
const editFormRef = ref()
const openEditDialog = () => {
  if (!details.value) return
  Object.assign(editForm, {
    CommodityId: details.value.CommodityId,
    FoodcommoditiesId: details.value.FoodcommoditiesId,
    BatchNumber: details.value.BatchNumber,
    ShelfLifeDays: details.value.ShelfLifeDays,
    ProductionLicense: details.value.ProductionLicense,
    Manufacturer: details.value.Manufacturer,
    CoverImageUrl: details.value.CoverImageUrl,
    Perfect: details.value.Perfect,
    Founder: details.value.Founder,
    Modifier: localStorage.getItem('Username') || '',
    CreateTime: details.value.CreateTime,
    IsDelete: details.value.IsDelete ?? false,
    Inspectionreport: details.value.Inspectionreport
  })
  editDialogVisible.value = true
}
const handleEditSave = async () => {
  try {
    const res = await CommodityInfoWrite.put('/api/Commodity/UpdateCommodity', editForm)
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      editDialogVisible.value = false
      fetchDetails() // 刷新详情
    } else {
      ElMessage.error(res.data.message || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

// 导出溯源码弹窗相关
const exportDialogVisible = ref(false)
const exportForm = reactive({
  CommodityId: null,
  QrCodeSize: 300,
  Format: 'PNG',
  ExportCount: 1
})
const openExportDialog = () => {
  exportDialogVisible.value = true
  exportForm.CommodityId = details.value?.CommodityId
  exportForm.ExportCount = 1
}
const handleExport = async () => {
  try {
    const res = await CommodityInfoRead.post('/api/Commodity/ExportTraceabilityCode', exportForm)
    if (res.data && res.data.code === 200) {
      const { CommodityId, QrCodeSize, Format } = exportForm
      const downloadRes = await CommodityInfoRead.get('/api/Commodity/DownloadTraceabilityQrCode', {
        params: { commodityId: CommodityId, size: QrCodeSize, format: Format },
        responseType: 'blob'
      })
      const contentType = downloadRes.headers['content-type']
      let fileExt = 'png'
      if (Format.toLowerCase() === 'jpg' || Format.toLowerCase() === 'jpeg') fileExt = 'jpg'
      if (contentType && contentType.indexOf('zip') > -1) fileExt = 'zip'
      const fileName = `溯源码_${CommodityId}.${fileExt}`
      const blob = new Blob([downloadRes.data])
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      a.click()
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
      exportDialogVisible.value = false
    } else {
      ElMessage.error(res.data.message || '溯源码生成失败')
    }
  } catch (e) {
    ElMessage.error('导出失败')
  }
}

// 产品检验报告图片上传相关

const uploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadImages'
interface ReportFileItem {
  name: string;
  url: string;
  status: string;
}
const reportFileList = ref<ReportFileItem[]>([])
// 上传成功回调，自动回显图片
const handleReportUploadSuccess = async (
  response: any,
  file: any,
  fileList: ReportFileItem[]
) => {
  if (response && response.paths) {
    response.paths.forEach((path: string) => {
      reportFileList.value.push({
        name: path.split('/').pop() || '',
        url: path.startsWith('http') ? path : CommodityInfoWrite.defaults.baseURL + path,
        status: 'done'
      })
    })
    reportFileList.value = reportFileList.value.slice(0, 9)
    const allPaths = reportFileList.value.map((f: ReportFileItem) => {
      const url: string = (f.url || '').replace(CommodityInfoWrite.defaults.baseURL as string, '')
      return url.startsWith('/') ? url : '/' + url
    })
    // 明确传递所有后端要求字段，避免Inspectionreport被旧值覆盖
    await CommodityInfoWrite.put('/api/Commodity/UpdateCommodity', {
      CommodityId: details.value.CommodityId,
      FoodcommoditiesId: details.value.FoodcommoditiesId,
      BatchNumber: details.value.BatchNumber,
      ShelfLifeDays: details.value.ShelfLifeDays,
      ProductionLicense: details.value.ProductionLicense,
      Manufacturer: details.value.Manufacturer,
      CoverImageUrl: details.value.CoverImageUrl,
      Perfect: details.value.Perfect,
      Founder: details.value.Founder,
      Modifier: localStorage.getItem('Username') || '',
      CreateTime: details.value.CreateTime,
      IsDelete: details.value.IsDelete ?? false,
      Inspectionreport: allPaths.join(',')
    })
    fetchDetails()
  }
}
// 删除图片回调
const handleReportRemove = async (
  file: ReportFileItem,
  fileList: ReportFileItem[]
) => {
  reportFileList.value = fileList
  const allPaths = reportFileList.value.map((f: ReportFileItem) => {
    const url: string = (f.url || '').replace(CommodityInfoWrite.defaults.baseURL as string, '')
    return url.startsWith('/') ? url : '/' + url
  })
  await CommodityInfoWrite.put('/api/Commodity/UpdateCommodity', {
    CommodityId: details.value.CommodityId,
    FoodcommoditiesId: details.value.FoodcommoditiesId,
    BatchNumber: details.value.BatchNumber,
    ShelfLifeDays: details.value.ShelfLifeDays,
    ProductionLicense: details.value.ProductionLicense,
    Manufacturer: details.value.Manufacturer,
    CoverImageUrl: details.value.CoverImageUrl,
    Perfect: details.value.Perfect,
    Founder: details.value.Founder,
    Modifier: localStorage.getItem('Username') || '',
    CreateTime: details.value.CreateTime,
    IsDelete: details.value.IsDelete ?? false,
    Inspectionreport: allPaths.join(',')
  })
  fetchDetails()
}
// 上传前校验
const beforeReportUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (reportFileList.value.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  if (!details.value?.CommodityId) {
    ElMessage.error('商品ID缺失，无法上传')
    return false
  }
  return true
}

// 获取养殖信息
const fetchAquacultureInfo = async (foodcommoditiesId: number | string) => {
  if (!foodcommoditiesId) return
  try {
    const res = await CommodityInfoRead.get('/api/Aquaculture/GetAquacultureByCommodityName', {
      params: { FoodcommoditiesId: foodcommoditiesId }
    })
    if (res.data && res.data.code === 200 && res.data.data) {
      const d = res.data.data
      aquacultureInfo.value = {
        AquacultureId: d.AquacultureId ?? 0,
        Breed: d.Breed ?? '',
        FoodcommoditiesId: d.FoodcommoditiesId ?? 0,
        Source: d.Source ?? '',
        FeedingDays: d.FeedingDays ?? 0,
        FeedBrand: d.FeedBrand ?? '',
        ResponsiblePerson: d.ResponsiblePerson ?? '',
        OutDate: d.OutDate ?? '',
        CreateTime: d.CreateTime ?? '',
        UpdateTime: d.UpdateTime ?? '',
        IsDelete: d.IsDelete ?? false
      }
      // 动检证图片回显
      if (d.DynamicInspectionImages) {
        dynamicInspectionFileList.value = d.DynamicInspectionImages
          .split(',')
          .filter((url: string) => Boolean(url))
          .map((url: string, idx: number) => ({
            name: `图片${idx + 1}`,
            url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
            status: 'done'
          }))
      } else {
        dynamicInspectionFileList.value = []
      }
      // 在fetchAquacultureInfo加载完养殖信息后调用
      if (d.AquacultureId) {
        await fetchDynamicInspectionImages(d.AquacultureId)
      }
    } else {
      aquacultureInfo.value = {
        AquacultureId: 0,
        Breed: '',
        FoodcommoditiesId: 0,
        Source: '',
        FeedingDays: 0,
        FeedBrand: '',
        ResponsiblePerson: '',
        OutDate: '',
        CreateTime: '',
        UpdateTime: '',
        IsDelete: false
      } // 赋默认空对象，保证模板可渲染且类型安全
      dynamicInspectionFileList.value = []
    }
  } catch (e) {
    aquacultureInfo.value = {
      AquacultureId: 0,
      Breed: '',
      FoodcommoditiesId: 0,
      Source: '',
      FeedingDays: 0,
      FeedBrand: '',
      ResponsiblePerson: '',
      OutDate: '',
      CreateTime: '',
      UpdateTime: '',
      IsDelete: false
    } // 赋默认空对象，保证模板可渲染且类型安全
    dynamicInspectionFileList.value = []
  }
}

const activeTab = ref('aquaculture')

// 新增格式化函数，精确到时分秒
function formatDateTime(val: string | undefined): string {
  if (!val) return ''
  // 兼容2025-07-01和2025-07-01T00:00:00等格式
  // 只返回前10位（YYYY-MM-DD）
  return val.slice(0, 10)
}

// 时间格式化函数，支持"YYYY年M月D日"格式
function formatDateTimeZh(val: string | undefined): string {
  if (!val) return ''
  const d = new Date(val)
  if (isNaN(d.getTime())) return ''
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
}

// 编辑养殖信息弹窗相关
const editAquacultureDialogVisible = ref(false)
interface EditAquacultureForm {
  AquacultureId: number;
  Breed: string;
  FoodcommoditiesId: number;
  Source: string;
  FeedingDays: number;
  FeedBrand: string;
  ResponsiblePerson: string;
  OutDate: string;
  CreateTime: string;
  UpdateTime: string;
  IsDelete: boolean;
}
const editAquacultureForm = reactive<EditAquacultureForm>({
  AquacultureId: 0,
  Breed: '',
  FoodcommoditiesId: 0,
  Source: '',
  FeedingDays: 0,
  FeedBrand: '',
  ResponsiblePerson: '',
  OutDate: '',
  CreateTime: '',
  UpdateTime: '',
  IsDelete: false
})
const openEditAquacultureDialog = () => {
  if (!aquacultureInfo.value) return
  Object.assign(editAquacultureForm, {
    AquacultureId: Number((aquacultureInfo.value as any).AquacultureId) || 0,
    Breed: (aquacultureInfo.value as any).Breed || '',
    FoodcommoditiesId: Number((aquacultureInfo.value as any).FoodcommoditiesId) || 0,
    Source: (aquacultureInfo.value as any).Source || '',
    FeedingDays: Number((aquacultureInfo.value as any).FeedingDays) || 0,
    FeedBrand: (aquacultureInfo.value as any).FeedBrand || '',
    ResponsiblePerson: (aquacultureInfo.value as any).ResponsiblePerson || '',
    OutDate: (aquacultureInfo.value as AquacultureInfo).OutDate ? (aquacultureInfo.value as AquacultureInfo).OutDate!.slice(0, 19) : '',
    CreateTime: (aquacultureInfo.value as any).CreateTime ? (aquacultureInfo.value as any).CreateTime.slice(0, 19) : '',
    UpdateTime: (aquacultureInfo.value as any).UpdateTime ? (aquacultureInfo.value as any).UpdateTime.slice(0, 19) : '',
    IsDelete: (aquacultureInfo.value as any).IsDelete === undefined ? false : (aquacultureInfo.value as any).IsDelete
  })
  // 如果OutDate为null或空，确保editAquacultureForm.OutDate为''
  if (!aquacultureInfo.value.OutDate) editAquacultureForm.OutDate = ''
  editAquacultureDialogVisible.value = true
}
const handleSaveAquaculture = async () => {
  try {
    const params: any = {
      AquacultureId: Number(editAquacultureForm.AquacultureId),
      Breed: editAquacultureForm.Breed,
      FoodcommoditiesId: details.value.FoodcommoditiesId, // 必须为真实ID
      Source: editAquacultureForm.Source,
      FeedingDays: Number(editAquacultureForm.FeedingDays),
      FeedBrand: editAquacultureForm.FeedBrand,
      ResponsiblePerson: editAquacultureForm.ResponsiblePerson,
      OutDate: editAquacultureForm.OutDate || new Date().toISOString().slice(0, 10),
      CreateTime: new Date().toISOString(),
      UpdateTime: new Date().toISOString(),
      IsDelete: false
    }
    let res
    if (!params.AquacultureId || params.AquacultureId === 0) {
      // 无数据时自动新增
      res = await CommodityInfoWrite.post('/api/Aquaculture/AddAquaculture', params)
    } else {
      // 有数据时自动修改
      res = await CommodityInfoWrite.post('/api/Aquaculture/UpdateAquaculture', params)
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success(params.AquacultureId === 0 ? '养殖信息新增成功' : '养殖信息修改成功')
      await fetchAquacultureInfo(details.value.FoodcommoditiesId)
      editAquacultureDialogVisible.value = false
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

// 新增保健信息相关
interface HealthcareItem {
  HealthcareId?: number
  AquacultureId: number
  Feeding_days: string
  Health_care_methods: string
  Method: string
  IsDelete?: boolean
  _edit?: boolean
  _isNew?: boolean
}
const healthcareList = ref<HealthcareItem[]>([])

const fetchHealthcareList = async () => {
  if (!aquacultureInfo.value?.AquacultureId) return
  const res = await CommodityInfoRead.get('/api/Aquaculture/GetHealthcareByAquacultureId', {
    params: { aquacultureId: aquacultureInfo.value.AquacultureId }
  })
  if (res.data && res.data.code === 200) {
    healthcareList.value = (res.data.data || []).map((item: any) => ({ ...item, _edit: false }))
  }
}

const addHealthcareRow = () => {
  healthcareList.value.push({
    AquacultureId: aquacultureInfo.value?.AquacultureId || 0,
    Feeding_days: '',
    Health_care_methods: '',
    Method: '',
    _edit: true,
    _isNew: true
  })
}

const editHealthcareRow = (row: HealthcareItem) => {
  row._edit = true
}

const cancelHealthcareRow = (row: HealthcareItem) => {
  if (row._isNew) {
    healthcareList.value = healthcareList.value.filter(r => r !== row)
  } else {
    row._edit = false
  }
}

const deleteHealthcareRow = async (row: HealthcareItem) => {
  if (!row.HealthcareId) {
    // 新增未保存的直接本地删除
    healthcareList.value = healthcareList.value.filter(r => r !== row)
    ElMessage.success('删除成功')
    return
  }
  try {
    const res = await CommodityInfoWrite.delete('/api/Aquaculture/DeletHealthcare', { data: { HealthcareId: row.HealthcareId } })
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || '删除成功')
      await fetchHealthcareList()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

const saveHealthcareRow = async () => {
  // 校验所有行
  for (const row of healthcareList.value) {
    if (!row.Feeding_days || !/^[0-9]{1,5}$/.test(row.Feeding_days)) {
      ElMessage.warning('请填写正确的饲养天数')
      return
    }
    if (!row.Health_care_methods || /[\\/?><.,;:'\"!@#$%^&*()_+=-]/.test(row.Health_care_methods) || row.Health_care_methods.length > 30) {
      ElMessage.warning('请填写正确的保健方式')
      return
    }
    if (!row.Method || /[\\/?><.,;:'\"!@#$%^&*()_+=-]/.test(row.Method) || row.Method.length > 30) {
      ElMessage.warning('请填写正确的保健方法')
      return
    }
  }
  // 组装参数
  const params = {
    AquacultureId: aquacultureInfo.value?.AquacultureId || 0,
    Items: healthcareList.value.map(row => ({
      HealthcareId: row.HealthcareId || 0,
      Feeding_days: Number(row.Feeding_days),
      Health_care_methods: row.Health_care_methods,
      Method: row.Method
    }))
  }
  try {
    const res = await CommodityInfoWrite.post('/api/Aquaculture/BatchAddHealthcare', params)
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      healthcareList.value.forEach(r => { r._edit = false; r._isNew = false })
      await fetchHealthcareList()
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const onInputNumber = (row: HealthcareItem) => {
  row.Feeding_days = row.Feeding_days.replace(/[^0-9]/g, '').slice(0, 5)
}
const onInputText = (row: HealthcareItem, key: 'Health_care_methods' | 'Method') => {
  row[key] = row[key].replace(/[\\/?><.,;:'\"!@#$%^&*()_+=-]/g, '').slice(0, 30)
}

watch(() => aquacultureInfo.value?.AquacultureId, fetchHealthcareList, { immediate: true })

// 动检证图片上传相关
const dynamicInspectionUploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadDynamicInspectionImages'
const dynamicInspectionFileList = ref<any[]>([])
const beforeDynamicInspectionUpload = (file: File) => {
  if (!aquacultureInfo.value?.AquacultureId) {
    ElMessage.error('请先保存养殖信息');
    return false;
  }
  if (dynamicInspectionFileList.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}
const handleDynamicInspectionUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response && response.code === 200) {
    ElMessage.success('上传成功');
    // 上传成功后强制刷新，保证fileList和后端一致
    fetchDynamicInspectionImages(aquacultureInfo.value?.AquacultureId)
  } else {
    ElMessage.error(response?.msg || '上传失败');
  }
}
const handleDynamicInspectionRemove = async (file: any, fileList: any[]) => {
  // 只保留后端真实存储的相对路径，保留开头的斜杠
  let url = file.url
  if (url.startsWith(CommodityInfoWrite.defaults.baseURL)) {
    url = url.replace(CommodityInfoWrite.defaults.baseURL, '')
  }
  // 不再去掉开头的斜杠，保证与后端一致
  try {
    const res = await CommodityInfoWrite.post('/api/Picture/DeleteDynamicInspectionPhotoImage', {
      AquacultureId: aquacultureInfo.value?.AquacultureId,
      ImageUrl: url
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchDynamicInspectionImages(aquacultureInfo.value?.AquacultureId)
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

// 动检证图片回显逻辑，替换为根据AquacultureId查找CertificateInfo
const fetchDynamicInspectionImages = async (aquacultureId: number) => {
  if (!aquacultureId) {
    dynamicInspectionFileList.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Aquaculture/GetCertificateInfoByAquacultureId', {
      params: { AquacultureId: aquacultureId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Dynamic_inspection) {
      dynamicInspectionFileList.value = res.data.data.Dynamic_inspection
        .split(',')
        .filter((url: string) => Boolean(url))
        .map((url: string, idx: number) => ({
          name: `图片${idx + 1}`,
          url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
          status: 'done'
        }))
    } else {
      dynamicInspectionFileList.value = []
    }
  } catch {
    dynamicInspectionFileList.value = []
  }
}

const fetchEnterpriseInfo = async (aquacultureId: number) => {
  if (!aquacultureId) {
    enterpriseInfo.value = null
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Aquaculture/GetEnterpriseInfoByAquacultureId', {
      params: { AquacultureId: aquacultureId }
    })
    if (res.data && res.data.code === 200 && res.data.data) {
      enterpriseInfo.value = res.data.data
    } else {
      enterpriseInfo.value = null
    }
  } catch {
    enterpriseInfo.value = null
  }
}

watch(() => aquacultureInfo.value?.AquacultureId, (id) => {
  if (id) fetchEnterpriseInfo(id)
}, { immediate: true })

// 企业信息弹窗相关
const enterpriseDialogVisible = ref(false)
const enterpriseForm = reactive({
  EnterpriseId: 0,
  AquacultureId: 0,
  Breeding_farm: '',
  Person_in_charge: '',
  Numberbooksstock: 0,
  IsDelete: false
})

const openEnterpriseDialog = () => {
  // 有企业信息则反填，无则清空
  if (enterpriseInfo.value && enterpriseInfo.value.EnterpriseId) {
    Object.assign(enterpriseForm, {
      EnterpriseId: enterpriseInfo.value.EnterpriseId,
      AquacultureId: enterpriseInfo.value.AquacultureId,
      Breeding_farm: enterpriseInfo.value.Breeding_farm,
      Person_in_charge: enterpriseInfo.value.Person_in_charge,
      Numberbooksstock: enterpriseInfo.value.Numberbooksstock,
      IsDelete: enterpriseInfo.value.IsDelete ?? false
    })
  } else {
    Object.assign(enterpriseForm, {
      EnterpriseId: 0,
      AquacultureId: aquacultureInfo.value?.AquacultureId || 0,
      Breeding_farm: '',
      Person_in_charge: '',
      Numberbooksstock: 0,
      IsDelete: false
    })
  }
  enterpriseDialogVisible.value = true
}

const handleEnterpriseSave = async () => {
  try {
    let res
    if (enterpriseInfo.value && enterpriseInfo.value.EnterpriseId) {
      // 修改
      res = await CommodityInfoWrite.post('/api/Aquaculture/UpdateEnterpriseInfo', enterpriseForm)
    } else {
      // 新增
      res = await CommodityInfoWrite.post('/api/Aquaculture/AddEnterpriseInfo', enterpriseForm)
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || '操作成功')
      enterpriseDialogVisible.value = false
      fetchEnterpriseInfo(enterpriseForm.AquacultureId)
    } else {
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

const enterprisePhotoUploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadEnterprisePhotoImages'
const enterprisePhotoFileList = ref<any[]>([])

const beforeEnterprisePhotoUpload = (file: File) => {
  if (!aquacultureInfo.value?.AquacultureId) {
    ElMessage.error('请先保存养殖信息');
    return false;
  }
  if (enterprisePhotoFileList.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

const handleEnterprisePhotoUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response && response.code === 200) {
    ElMessage.success('上传成功');
    fetchEnterprisePhotoImages(aquacultureInfo.value?.AquacultureId)
  } else {
    ElMessage.error(response?.msg || '上传失败');
  }
}

const handleEnterprisePhotoRemove = async (file: any, fileList: any[]) => {
  // 直接调用后端删除接口
  const url = file.url.replace(CommodityInfoWrite.defaults.baseURL, '')
  try {
    const res = await CommodityInfoWrite.post('/api/Picture/DeleteEnterprisePhotoImage', {
      AquacultureId: aquacultureInfo.value?.AquacultureId,
      ImageUrl: url
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchEnterprisePhotoImages(aquacultureInfo.value?.AquacultureId)
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

const fetchEnterprisePhotoImages = async (aquacultureId: number) => {
  if (!aquacultureId) {
    enterprisePhotoFileList.value = []
    return
  }
  try {
    // 企业照片回显接口为GetCertificateInfoByAquacultureId，字段Enterprise_photo
    const res = await CommodityInfoRead.get('/api/Aquaculture/GetCertificateInfoByAquacultureId', {
      params: { AquacultureId: aquacultureId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Enterprise_photo) {
      enterprisePhotoFileList.value = res.data.data.Enterprise_photo
        .split(',')
        .filter((url: string) => Boolean(url))
        .map((url: string, idx: number) => ({
          name: `图片${idx + 1}`,
          url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
          status: 'done'
        }))
    } else {
      enterprisePhotoFileList.value = []
    }
  } catch {
    enterprisePhotoFileList.value = []
  }
}

watch(() => aquacultureInfo.value?.AquacultureId, (id) => {
  if (id) fetchEnterprisePhotoImages(id)
}, { immediate: true })

const slaughterDialogVisible = ref(false)
const slaughterForm = reactive({
  SlaughterId: 0,
  AquacultureId: 0,
  BatchNo: '',
  AvgWeight: '',
  ArriveTime: '' as string | Date,
  SlaughterTime: '' as string | Date,
  IsDelete: false
})
const slaughterFormRef = ref()

const openSlaughterDialog = () => {
  if (slaughterInfo.value) {
    // 修改，反填，时间转Date
    Object.assign(slaughterForm, {
      SlaughterId: slaughterInfo.value.SlaughterId,
      AquacultureId: slaughterInfo.value.AquacultureId,
      BatchNo: slaughterInfo.value.BatchNo,
      AvgWeight: slaughterInfo.value.AvgWeight,
      ArriveTime: slaughterInfo.value.ArriveTime ? new Date(slaughterInfo.value.ArriveTime) : '',
      SlaughterTime: slaughterInfo.value.SlaughterTime ? new Date(slaughterInfo.value.SlaughterTime) : '',
      IsDelete: slaughterInfo.value.IsDelete ?? false
    })
  } else {
    // 新增，清空
    Object.assign(slaughterForm, {
      SlaughterId: 0,
      AquacultureId: aquacultureInfo.value?.AquacultureId || 0,
      BatchNo: '',
      AvgWeight: '',
      ArriveTime: '',
      SlaughterTime: '',
      IsDelete: false
    })
  }
  slaughterDialogVisible.value = true
}

// 批次号输入限制：只允许中英文、数字，最多30位
const onBatchNoInput = (val: string) => {
  // 只保留中英文、数字
  let filtered = val.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '')
  if (filtered.length > 30) filtered = filtered.slice(0, 30)
  slaughterForm.BatchNo = filtered
}
// 到厂均重输入限制：只允许数字，最多5位
const onAvgWeightInput = (val: string | number) => {
  let filtered = val.toString().replace(/[^0-9]/g, '')
  if (filtered.length > 5) filtered = filtered.slice(0, 5)
  slaughterForm.AvgWeight = filtered
}

const handleSaveSlaughter = async () => {
  // 校验批次号
  const batchNo = (slaughterForm.BatchNo || '').toString().trim()
  if (!batchNo) {
    ElMessage.warning('批次号不能为空')
    return
  }
  if (batchNo.length > 30) {
    ElMessage.warning('批次号最多30位')
    return
  }
  if (/[^ -\u4e00-\u9fa5a-zA-Z0-9]/.test(batchNo)) {
    ElMessage.warning('批次号只能输入中英文和数字，不能有特殊字符')
    return
  }
  // 校验到厂均重
  const avgWeight = slaughterForm.AvgWeight.toString().trim()
  if (!avgWeight) {
    ElMessage.warning('到厂均重不能为空')
    return
  }
  if (!/^[0-9]{1,5}$/.test(avgWeight)) {
    ElMessage.warning('到厂均重只能输入最多5位数字')
    return
  }
  // 校验时间
  if (!slaughterForm.ArriveTime) {
    ElMessage.warning('到厂时间不能为空')
    return
  }
  if (!slaughterForm.SlaughterTime) {
    ElMessage.warning('屠宰时间不能为空')
    return
  }
  // 时间转ISO字符串
  const buildSlaughterDto = () => ({
    ...slaughterForm,
    BatchNo: batchNo,
    AvgWeight: Number(avgWeight),
    ArriveTime: slaughterForm.ArriveTime instanceof Date ? slaughterForm.ArriveTime.toISOString() : slaughterForm.ArriveTime,
    SlaughterTime: slaughterForm.SlaughterTime instanceof Date ? slaughterForm.SlaughterTime.toISOString() : slaughterForm.SlaughterTime,
  })
  const params = buildSlaughterDto()
  console.log('提交屠宰信息参数', params)
  try {
    let res
    if (slaughterInfo.value) {
      // 修改
      res = await CommodityInfoWrite.put('/api/Slaughter/UpdateSlaughterInfo', params, { headers: { 'Content-Type': 'application/json' } })
    } else {
      // 新增
      res = await CommodityInfoWrite.post('/api/Slaughter/AddSlaughterInfo', params, { headers: { 'Content-Type': 'application/json' } })
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      slaughterDialogVisible.value = false
      fetchSlaughterInfo(slaughterForm.AquacultureId)
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const fetchSlaughterInfo = async (aquacultureId: number) => {
  if (!aquacultureId) {
    slaughterInfo.value = null
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Slaughter/GetSlaughterInfoByAquacultureId', {
      params: { AquacultureId: aquacultureId }
    })
    if (res.data && res.data.code === 200 && res.data.data) {
      slaughterInfo.value = res.data.data
    } else {
      slaughterInfo.value = null
    }
  } catch {
    slaughterInfo.value = null
  }
}

watch(() => aquacultureInfo.value?.AquacultureId, (id) => {
  if (id) fetchSlaughterInfo(id)
}, { immediate: true })

const slaughterQualificationFileList = ref<any[]>([])

const fetchSlaughterQualificationImages = async (slaughterId: number) => {
  if (!slaughterId) {
    slaughterQualificationFileList.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Slaughter/GetSlaughtercertificateSlaughterId', {
      params: { SlaughterId: slaughterId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Relevant_qualifications) {
      const urls = res.data.data.Relevant_qualifications.split(',').filter((url: string) => Boolean(url))
      slaughterQualificationFileList.value = urls.map((url: string, idx: number) => ({
        name: `图片${idx + 1}`,
        url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
        rawUrl: url // 用于删除
      }))
    } else {
      slaughterQualificationFileList.value = []
    }
  } catch {
    slaughterQualificationFileList.value = []
  }
}

watch(() => slaughterInfo.value?.SlaughterId, (id) => {
  if (id) fetchSlaughterQualificationImages(id)
}, { immediate: true })

const slaughterQualificationUploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadSlaughterQualificationImages'

const beforeSlaughterQualificationUpload = (file: File) => {
  if (!slaughterInfo.value?.SlaughterId) {
    ElMessage.error('请先保存屠宰信息');
    return false;
  }
  if (slaughterQualificationFileList.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

const handleSlaughterQualificationUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response && response.code === 200) {
    ElMessage.success('上传成功');
    fetchSlaughterQualificationImages(slaughterInfo.value?.SlaughterId)
  } else {
    ElMessage.error(response?.msg || '上传失败');
  }
}

const handleSlaughterQualificationRemove = async (file: any, fileList: any[]) => {
  if (!slaughterInfo.value?.SlaughterId || !file.rawUrl) return
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteSlaughterQualificationImage', {
      data: {
        SlaughterId: slaughterInfo.value.SlaughterId,
        ImageUrl: file.rawUrl
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchSlaughterQualificationImages(slaughterInfo.value.SlaughterId)
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

const slaughterEnterpriseInfo = ref<any>(null)
const slaughterEnterpriseDialogVisible = ref(false)
const slaughterEnterpriseForm = reactive({
  SlaughterhousEenterpriseId: 0,
  SlaughterId: 0,
  CompanyName: '',
  CompanyAddress: '',
  EstablishmentDate: '' as string | Date,
  CompanyProfile: '',
  IsDelte: false
})
const slaughterEnterpriseFormRef = ref()

const fetchSlaughterEnterpriseInfo = async (slaughterId: number) => {
  if (!slaughterId) {
    slaughterEnterpriseInfo.value = null
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Slaughter/GetSlaughterhousEenterpriseSlaughterId', {
      params: { SlaughterId: slaughterId }
    })
    if (res.data && res.data.code === 200 && res.data.data) {
      slaughterEnterpriseInfo.value = res.data.data
    } else {
      slaughterEnterpriseInfo.value = null
    }
  } catch {
    slaughterEnterpriseInfo.value = null
  }
}

watch(() => slaughterInfo.value?.SlaughterId, (id) => {
  if (id) fetchSlaughterEnterpriseInfo(id)
}, { immediate: true })

const openSlaughterEnterpriseDialog = () => {
  if (slaughterEnterpriseInfo.value) {
    // 反填，时间转Date
    Object.assign(slaughterEnterpriseForm, {
      SlaughterhousEenterpriseId: slaughterEnterpriseInfo.value.SlaughterhousEenterpriseId,
      SlaughterId: slaughterEnterpriseInfo.value.SlaughterId,
      CompanyName: slaughterEnterpriseInfo.value.CompanyName,
      CompanyAddress: slaughterEnterpriseInfo.value.CompanyAddress,
      EstablishmentDate: slaughterEnterpriseInfo.value.EstablishmentDate ? new Date(slaughterEnterpriseInfo.value.EstablishmentDate) : '',
      CompanyProfile: slaughterEnterpriseInfo.value.CompanyProfile,
      IsDelte: slaughterEnterpriseInfo.value.IsDelte ?? false
    })
  } else {
    Object.assign(slaughterEnterpriseForm, {
      SlaughterhousEenterpriseId: 0,
      SlaughterId: slaughterInfo.value?.SlaughterId || 0,
      CompanyName: '',
      CompanyAddress: '',
      EstablishmentDate: '',
      CompanyProfile: '',
      IsDelte: false
    })
  }
  slaughterEnterpriseDialogVisible.value = true
}

// 校验规则
const validateCompanyName = (val: string) => {
  if (!val) return '公司名称不能为空'
  if (val.length > 30) return '公司名称最多30字符'
  if (/[^\u4e00-\u9fa5a-zA-Z0-9（）()·\s-]/.test(val)) return '公司名称不能有特殊符号'
  return ''
}
const validateCompanyAddress = (val: string) => {
  if (!val) return '公司地址不能为空'
  if (val.length > 100) return '公司地址最多100字符'
  if (/[^\u4e00-\u9fa5a-zA-Z0-9（）()·,，—_\s-]/.test(val)) return '公司地址不能有特殊符号'
  return ''
}
const validateCompanyProfile = (val: string) => {
  if (!val) return ''
  if (val.length > 500) return '公司简介最多500字符'
  if (/[^\u4e00-\u9fa5a-zA-Z0-9（）()·,，—_。；；、\s-]/.test(val)) return '公司简介不能有特殊符号'
  return ''
}

const handleSaveSlaughterEnterprise = async () => {
  // 校验
  const nameMsg = validateCompanyName(slaughterEnterpriseForm.CompanyName)
  if (nameMsg) { ElMessage.warning(nameMsg); return }
  const addrMsg = validateCompanyAddress(slaughterEnterpriseForm.CompanyAddress)
  if (addrMsg) { ElMessage.warning(addrMsg); return }
  if (!slaughterEnterpriseForm.EstablishmentDate) { ElMessage.warning('成立时间不能为空'); return }
  const profileMsg = validateCompanyProfile(slaughterEnterpriseForm.CompanyProfile)
  if (profileMsg) { ElMessage.warning(profileMsg); return }
  // 时间转本地YYYY-MM-DDT00:00:00，避免时区偏移
  const buildDto = () => {
    let dateStr = ''
    if (slaughterEnterpriseForm.EstablishmentDate instanceof Date) {
      const y = slaughterEnterpriseForm.EstablishmentDate.getFullYear();
      const m = slaughterEnterpriseForm.EstablishmentDate.getMonth() + 1;
      const d = slaughterEnterpriseForm.EstablishmentDate.getDate();
      dateStr = `${y}-${m.toString().padStart(2, '0')}-${d.toString().padStart(2, '0')}T00:00:00`;
    } else {
      dateStr = slaughterEnterpriseForm.EstablishmentDate;
    }
    return {
      ...slaughterEnterpriseForm,
      EstablishmentDate: dateStr
    }
  }
  const params = buildDto()
  try {
    let res
    if (slaughterEnterpriseInfo.value) {
      res = await CommodityInfoWrite.put('/api/Slaughter/UpdateSlaughterhousEenterprise/UpdateSlaughterhousEenterprise', params, { headers: { 'Content-Type': 'application/json' } })
    } else {
      res = await CommodityInfoWrite.post('/api/Slaughter/AddSlaughterhousEenterprise/AddSlaughterhousEenterprise', params, { headers: { 'Content-Type': 'application/json' } })
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      slaughterEnterpriseDialogVisible.value = false
      fetchSlaughterEnterpriseInfo(slaughterEnterpriseForm.SlaughterId)
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const slaughterEnterprisePhotoFileList = ref<any[]>([])
const slaughterEnterprisePhotoUploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadSlaughterEnterprisePhotoImagesAsync'

// 回显：根据屠宰企业Id查图片
const fetchSlaughterEnterprisePhotoImages = async (slaughterhousEenterpriseId: number) => {
  if (!slaughterhousEenterpriseId) {
    slaughterEnterprisePhotoFileList.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Slaughter/GetSlaughtercertificateSlaughtercertificateId', {
      params: { SlaughterhousEenterpriseId: slaughterhousEenterpriseId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Enterprise_Photo) {
      const urls = (res.data.data.Enterprise_Photo as string).split(',').filter((url: string) => Boolean(url))
      const baseUrl = (CommodityInfoWrite.defaults.baseURL || '').replace(/\/$/, '')
      slaughterEnterprisePhotoFileList.value = urls.map((url: string, idx: number) => ({
        name: `图片${idx + 1}`,
        url: url.startsWith('http') ? url : baseUrl + url,
        status: 'done',
        rawUrl: url // 用于删除
      }))
    } else {
      slaughterEnterprisePhotoFileList.value = []
    }
    // 调试输出
    console.log('企业图片file-list:', slaughterEnterprisePhotoFileList.value);
  } catch {
    slaughterEnterprisePhotoFileList.value = []
  }
}

// 监听企业Id自动刷新
watch(() => slaughterEnterpriseInfo.value?.SlaughterhousEenterpriseId, (id) => {
  if (id) fetchSlaughterEnterprisePhotoImages(id)
}, { immediate: true })

const beforeSlaughterEnterprisePhotoUpload = (file: File) => {
  if (!slaughterEnterpriseInfo.value?.SlaughterhousEenterpriseId) {
    ElMessage.error('请先保存企业信息');
    return false;
  }
  if (slaughterEnterprisePhotoFileList.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

const handleSlaughterEnterprisePhotoUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response && response.code === 200) {
    ElMessage.success('上传成功');
    fetchSlaughterEnterprisePhotoImages(slaughterEnterpriseInfo.value?.SlaughterhousEenterpriseId)
  } else {
    ElMessage.error(response?.msg || '上传失败');
  }
}

const handleSlaughterEnterprisePhotoRemove = async (file: any, fileList: any[]) => {
  if (!slaughterEnterpriseInfo.value?.SlaughterhousEenterpriseId || !file.rawUrl) return
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteSlaughterEnterprisePhotoImage', {
      data: {
        SlaughterhousEenterpriseId: slaughterEnterpriseInfo.value.SlaughterhousEenterpriseId,
        ImageUrl: file.rawUrl
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchSlaughterEnterprisePhotoImages(slaughterEnterpriseInfo.value.SlaughterhousEenterpriseId)
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

// 深加工信息相关
const processingInfo = ref<any>(null)
const processingDialogVisible = ref(false)
const processingForm = reactive({
  ProcessingID: 0,
  SlaughterId: 0,
  GroupName: '',
  ResponsiblePerson: '',
  Food_safety: '',
  IsDelete: false
})
const processingFormRef = ref()

// 校验规则
const validateGroupName = (val: string) => {
  if (!val) return '班组不能为空'
  if (val.length > 30) return '班组最多30字符'
  if (/[^\u4e00-\u9fa5a-zA-Z0-9\s]/.test(val)) return '班组不能有特殊符号'
  return ''
}
const validateResponsiblePerson = (val: string) => {
  if (!val) return '负责人不能为空'
  if (val.length > 30) return '负责人最多30字符'
  if (/[^\u4e00-\u9fa5a-zA-Z\s]/.test(val)) return '负责人不能有特殊符号'
  return ''
}

// 查询深加工信息
const fetchProcessingInfo = async (slaughterId: number) => {
  if (!slaughterId) {
    processingInfo.value = null
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Processing/GetProcessingInfoBySlaughterId', {
      params: { SlaughterId: slaughterId }
    })
    if (res.data && res.data.code === 200 && res.data.data) {
      processingInfo.value = res.data.data
    } else {
      processingInfo.value = null
    }
  } catch {
    processingInfo.value = null
  }
}

watch(() => slaughterInfo.value?.SlaughterId, (id) => {
  if (id) fetchProcessingInfo(id)
}, { immediate: true })

const openProcessingDialog = () => {
  if (processingInfo.value) {
    Object.assign(processingForm, {
      ProcessingID: processingInfo.value.ProcessingID,
      SlaughterId: processingInfo.value.SlaughterId,
      GroupName: processingInfo.value.GroupName,
      ResponsiblePerson: processingInfo.value.ResponsiblePerson,
      Food_safety: processingInfo.value.Food_safety,
      IsDelete: processingInfo.value.IsDelete ?? false
    })
  } else {
    Object.assign(processingForm, {
      ProcessingID: 0,
      SlaughterId: slaughterInfo.value?.SlaughterId || 0,
      GroupName: '',
      ResponsiblePerson: '',
      Food_safety: '',
      IsDelete: false
    })
  }
  processingDialogVisible.value = true
}

const handleSaveProcessing = async () => {
  // 校验
  const groupMsg = validateGroupName(processingForm.GroupName)
  if (groupMsg) { ElMessage.warning(groupMsg); return }
  const personMsg = validateResponsiblePerson(processingForm.ResponsiblePerson)
  if (personMsg) { ElMessage.warning(personMsg); return }
  try {
    let res
    if (processingForm.ProcessingID) {
      // 修改
      res = await CommodityInfoWrite.put('/api/Processing/UpdateProcessingInfo', processingForm)
    } else {
      // 新增
      res = await CommodityInfoWrite.post('/api/Processing/AddProcessingInfo', {
        SlaughterId: processingForm.SlaughterId,
        GroupName: processingForm.GroupName,
        ResponsiblePerson: processingForm.ResponsiblePerson
      })
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      processingDialogVisible.value = false
      fetchProcessingInfo(processingForm.SlaughterId)
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch {
    ElMessage.error('保存失败')
  }
}

// 食品安全信息图片上传相关
const processingFoodSafetyFileList = ref<any[]>([])
const processingFoodSafetyUploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadProcessingFoodSafetyImages'

// 回显图片
const fetchProcessingFoodSafetyImages = (foodSafetyStr: string) => {
  if (!foodSafetyStr) {
    processingFoodSafetyFileList.value = []
    return
  }
  const baseUrl = (CommodityInfoWrite.defaults.baseURL || '').replace(/\/$/, '')
  const urls = foodSafetyStr.split(',').filter((url: string) => Boolean(url))
  processingFoodSafetyFileList.value = urls.map((url: string, idx: number) => ({
    name: `图片${idx + 1}`,
    url: url.startsWith('http') ? url : baseUrl + url,
    status: 'done',
    rawUrl: url // 用于删除
  }))
}

// 监听processingInfo变化自动回显
watch(() => processingInfo.value?.Food_safety, (val) => {
  fetchProcessingFoodSafetyImages(val || '')
}, { immediate: true })

const beforeProcessingFoodSafetyUpload = (file: File) => {
  if (!processingInfo.value?.ProcessingID) {
    ElMessage.error('请先保存深加工信息');
    return false;
  }
  if (processingFoodSafetyFileList.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

const handleProcessingFoodSafetyUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response && response.code === 200) {
    ElMessage.success('上传成功');
    // 重新查processingInfo，自动刷新图片
    fetchProcessingInfo(processingInfo.value.SlaughterId)
  } else {
    ElMessage.error(response?.msg || '上传失败');
  }
}

const handleProcessingFoodSafetyRemove = async (file: any, fileList: any[]) => {
  if (!processingInfo.value?.ProcessingID || !file.rawUrl) return
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteProcessingFoodSafetyPhotoImage', {
      data: {
        ProcessingID: processingInfo.value.ProcessingID,
        ImageUrl: file.rawUrl
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchProcessingInfo(processingInfo.value.SlaughterId)
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

const processingFoodSafetyUploadRef = ref()
function handleRemoveProcessingFoodSafetyFile(file: any) {
  processingFoodSafetyUploadRef.value.handleRemove(file)
}
function handlePreview(file: any) {
  // 可用el-image-preview或自定义预览逻辑
  window.open(file.url, '_blank')
}

const slaughterQualificationUploadRef = ref()
function handleRemoveSlaughterQualificationFile(file: any) {
  slaughterQualificationUploadRef.value.handleRemove(file)
}

// 供应商信息请求与渲染
const supplyInfo = ref(null)
async function fetchSupplyInfo(processingId: any) {
  if (!processingId) { supplyInfo.value = null; return }
  const res = await CommodityInfoRead.get('/api/Processing/GetSupplyofgoodsByProcessingId', {
    params: { ProcessingID: processingId as number }
  })
  if (res.data && res.data.code === 200) {
    supplyInfo.value = res.data.data
  } else {
    supplyInfo.value = null
  }
}
// 监听processingInfo变化自动请求供应商信息
watch(() => processingInfo.value?.ProcessingID, (id) => {
  if (id) fetchSupplyInfo(id as number)
}, { immediate: true })

// 供应商信息弹框相关
const supplierDialogVisible = ref(false)
const supplierDialogType = ref<'raw'|'aux'|'add'|'pack'>('raw')
const supplierForm = reactive({
  SupplyofgoodsId: undefined,
  ProcessingID: undefined,
  Raw_materials: '',
  Raw_Relevant_materials: '',
  Auxiliary_materials: '',
  Auxiliary_Relevant_materials: '',
  Additive: '',
  Additive_Relevant_materials: '',
  Packaging_materials: '',
  Packaging_Relevant_materials: '',
  IsDelete: false
})
const isAddRaw = ref(false) // 原料是否为新增

function openSupplierDialog(type: 'raw'|'aux'|'add'|'pack', supplyInfo: any, processingId: number) {
  supplierDialogType.value = type
  if (type === 'raw') {
    if (!supplyInfo?.SupplyofgoodsId) {
      // 新增原料
      isAddRaw.value = true
      supplierForm.ProcessingID = processingId
      supplierForm.Raw_materials = ''
      supplierForm.Raw_Relevant_materials = ''
      supplierForm.SupplyofgoodsId = undefined
      supplierForm.Auxiliary_materials = ''
      supplierForm.Auxiliary_Relevant_materials = ''
      supplierForm.Additive = ''
      supplierForm.Additive_Relevant_materials = ''
      supplierForm.Packaging_materials = ''
      supplierForm.Packaging_Relevant_materials = ''
      supplierForm.IsDelete = false
    } else {
      // 修改原料
      isAddRaw.value = false
      Object.assign(supplierForm, supplyInfo)
    }
  } else {
    // 其余只能修改
    isAddRaw.value = false
    Object.assign(supplierForm, supplyInfo)
  }
  supplierDialogVisible.value = true
}

async function handleSaveSupplier() {
  if (supplierDialogType.value === 'raw' && isAddRaw.value) {
    // 新增原料
    const params = {
      ProcessingID: supplierForm.ProcessingID,
      Raw_materials: supplierForm.Raw_materials
    }
    const res = await CommodityInfoWrite.post('/api/Processing/AddSupplyofgoodsInfo', params)
    if (res.data && res.data.code === 200) {
      ElMessage.success('原料添加成功')
      supplierDialogVisible.value = false
      fetchSupplyInfo(supplierForm.ProcessingID)
    } else {
      ElMessage.error(res.data?.msg || '添加失败')
    }
  } else {
    // 修改
    const res = await CommodityInfoWrite.put('/api/Processing/UpdateSupplyofgoodsInfo', supplierForm)
    if (res.data && res.data.code === 200) {
      ElMessage.success('供应商信息修改成功')
      supplierDialogVisible.value = false
      fetchSupplyInfo(supplierForm.ProcessingID)
    } else {
      ElMessage.error(res.data?.msg || '修改失败')
    }
  }
}

const rawMaterialsImages = ref<any[]>([])

// 回显图片
const fetchRawMaterialsImages = async (processingId: number) => {
  if (!processingId) {
    rawMaterialsImages.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Processing/GetSupplyofgoodsById', {
      params: { ProcessingID: processingId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Raw_Relevant_materials) {
      rawMaterialsImages.value = res.data.data.Raw_Relevant_materials
        .split(',')
        .filter((url: string) => Boolean(url))
        .map((url: string, idx: number) => ({
          name: `图片${idx + 1}`,
          url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
          status: 'done'
        }))
    } else {
      rawMaterialsImages.value = []
    }
  } catch {
    rawMaterialsImages.value = []
  }
}

// 页面加载和ProcessingID变化时自动回显
watch(() => processingInfo.value?.ProcessingID, (id) => {
  if (id) fetchRawMaterialsImages(id as number)
}, { immediate: true })

// 上传图片
const customRawMaterialsUpload = async (option: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('请先保存深加工信息');
    return option.onError(new Error('无ProcessingID'));
  }
  const formData = new FormData();
  formData.append('ProcessingID', processingId);
  formData.append('Files', option.file);
  try {
    const res = await CommodityInfoWrite.post('/api/Picture/UploadRawMaterialsImages', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (res.data && res.data.code === 200) {
      ElMessage.success('上传成功');
      fetchRawMaterialsImages(processingId);
      option.onSuccess(res.data);
    } else {
      ElMessage.error(res.data?.msg || '上传失败');
      option.onError(new Error(res.data?.msg || '上传失败'));
    }
  } catch (e) {
    ElMessage.error('上传失败');
    option.onError(e);
  }
}

// 删除图片
const handleRawMaterialsRemove = async (file: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('无ProcessingID，无法删除');
    return;
  }
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteRawMaterialsPhotoImage', {
      data: {
        ProcessingID: processingId,
        ImageUrl: file.url.replace(CommodityInfoWrite.defaults.baseURL, '')
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchRawMaterialsImages(processingId)
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

// 上传前校验
const beforeRawMaterialsUpload = (file: File) => {
  if (!processingInfo.value?.ProcessingID) {
    ElMessage.error('请先保存深加工信息');
    return false;
  }
  if (rawMaterialsImages.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

// 上传成功回调（可选，主要用于el-upload的on-success）
const handleRawMaterialsUploadSuccess = () => {
  // 实际刷新已在customRawMaterialsUpload里做了
}

const auxMaterialsImages = ref<any[]>([])

// 回显辅料图片
const fetchAuxMaterialsImages = async (processingId: number) => {
  if (!processingId) {
    auxMaterialsImages.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Processing/GetSupplyofgoodsById', {
      params: { ProcessingID: processingId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Auxiliary_Relevant_materials) {
      auxMaterialsImages.value = res.data.data.Auxiliary_Relevant_materials
        .split(',')
        .filter((url: string) => Boolean(url))
        .map((url: string, idx: number) => ({
          name: `图片${idx + 1}`,
          url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
          status: 'done'
        }))
    } else {
      auxMaterialsImages.value = []
    }
  } catch {
    auxMaterialsImages.value = []
  }
}

// 页面加载和ProcessingID变化时自动回显
watch(() => processingInfo.value?.ProcessingID, (id) => {
  if (id) fetchAuxMaterialsImages(id)
}, { immediate: true })

// 上传辅料图片
const customAuxMaterialsUpload = async (option: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('请先保存深加工信息');
    return option.onError(new Error('无ProcessingID'));
  }
  const formData = new FormData();
  formData.append('ProcessingID', processingId);
  formData.append('Files', option.file);
  try {
    const res = await CommodityInfoWrite.post('/api/Picture/UploadAuxiliaryMaterialsImages', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (res.data && res.data.code === 200) {
      ElMessage.success('上传成功');
      fetchAuxMaterialsImages(processingId);
      option.onSuccess(res.data);
    } else {
      ElMessage.error(res.data?.msg || '上传失败');
      option.onError(new Error(res.data?.msg || '上传失败'));
    }
  } catch (e) {
    ElMessage.error('上传失败');
    option.onError(e);
  }
}

// 删除辅料图片
const handleAuxMaterialsRemove = async (file: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('无ProcessingID，无法删除');
    return;
  }
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteAuxiliaryMaterialsPhotoImage', {
      data: {
        ProcessingID: processingId,
        ImageUrl: file.url.replace(CommodityInfoWrite.defaults.baseURL, '')
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchAuxMaterialsImages(processingId)
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

// 上传前校验
const beforeAuxMaterialsUpload = (file: File) => {
  if (!processingInfo.value?.ProcessingID) {
    ElMessage.error('请先保存深加工信息');
    return false;
  }
  if (auxMaterialsImages.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

// 上传成功回调（可选，主要用于el-upload的on-success）
const handleAuxMaterialsUploadSuccess = () => {
  // 实际刷新已在customAuxMaterialsUpload里做了
}

const addMaterialsImages = ref<any[]>([])
const packMaterialsImages = ref<any[]>([])

// 回显添加剂图片
const fetchAddMaterialsImages = async (processingId: number) => {
  if (!processingId) {
    addMaterialsImages.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Processing/GetSupplyofgoodsById', {
      params: { ProcessingID: processingId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Additive_Relevant_materials) {
      addMaterialsImages.value = res.data.data.Additive_Relevant_materials
        .split(',')
        .filter((url: string) => Boolean(url))
        .map((url: string, idx: number) => ({
          name: `图片${idx + 1}`,
          url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
          status: 'done'
        }))
    } else {
      addMaterialsImages.value = []
    }
  } catch {
    addMaterialsImages.value = []
  }
}

// 回显包材图片
const fetchPackMaterialsImages = async (processingId: number) => {
  if (!processingId) {
    packMaterialsImages.value = []
    return
  }
  try {
    const res = await CommodityInfoRead.get('/api/Processing/GetSupplyofgoodsById', {
      params: { ProcessingID: processingId }
    })
    if (res.data && res.data.code === 200 && res.data.data && res.data.data.Packaging_Relevant_materials) {
      packMaterialsImages.value = res.data.data.Packaging_Relevant_materials
        .split(',')
        .filter((url: string) => Boolean(url))
        .map((url: string, idx: number) => ({
          name: `图片${idx + 1}`,
          url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
          status: 'done'
        }))
    } else {
      packMaterialsImages.value = []
    }
  } catch {
    packMaterialsImages.value = []
  }
}

// 页面加载和ProcessingID变化时自动回显
watch(() => processingInfo.value?.ProcessingID, (id) => {
  if (id) {
    fetchAddMaterialsImages(id)
    fetchPackMaterialsImages(id)
  }
}, { immediate: true })

// 上传添加剂图片
const customAddMaterialsUpload = async (option: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('请先保存深加工信息');
    return option.onError(new Error('无ProcessingID'));
  }
  const formData = new FormData();
  formData.append('ProcessingID', processingId);
  formData.append('Files', option.file);
  try {
    const res = await CommodityInfoWrite.post('/api/Picture/UploadAdditiveMaterialsImages', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (res.data && res.data.code === 200) {
      ElMessage.success('上传成功');
      fetchAddMaterialsImages(processingId);
      option.onSuccess(res.data);
    } else {
      ElMessage.error(res.data?.msg || '上传失败');
      option.onError(new Error(res.data?.msg || '上传失败'));
    }
  } catch (e) {
    ElMessage.error('上传失败');
    option.onError(e);
  }
}

// 删除添加剂图片
const handleAddMaterialsRemove = async (file: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('无ProcessingID，无法删除');
    return;
  }
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteAdditiveMaterialsPhotoImage', {
      data: {
        ProcessingID: processingId,
        ImageUrl: file.url.replace(CommodityInfoWrite.defaults.baseURL, '')
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchAddMaterialsImages(processingId)
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

// 上传前校验
const beforeAddMaterialsUpload = (file: File) => {
  if (!processingInfo.value?.ProcessingID) {
    ElMessage.error('请先保存深加工信息');
    return false;
  }
  if (addMaterialsImages.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

// 上传成功回调（可选，主要用于el-upload的on-success）
const handleAddMaterialsUploadSuccess = () => {
  // 实际刷新已在customAddMaterialsUpload里做了
}

// 上传包材图片
const customPackMaterialsUpload = async (option: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('请先保存深加工信息');
    return option.onError(new Error('无ProcessingID'));
  }
  const formData = new FormData();
  formData.append('ProcessingID', processingId);
  formData.append('Files', option.file);
  try {
    const res = await CommodityInfoWrite.post('/api/Picture/UploadPackagingMaterialsImages', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (res.data && res.data.code === 200) {
      ElMessage.success('上传成功');
      fetchPackMaterialsImages(processingId);
      option.onSuccess(res.data);
    } else {
      ElMessage.error(res.data?.msg || '上传失败');
      option.onError(new Error(res.data?.msg || '上传失败'));
    }
  } catch (e) {
    ElMessage.error('上传失败');
    option.onError(e);
  }
}

// 删除包材图片
const handlePackMaterialsRemove = async (file: any) => {
  const processingId = processingInfo.value?.ProcessingID
  if (!processingId) {
    ElMessage.error('无ProcessingID，无法删除');
    return;
  }
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeletePackagingMaterialsPhotoImage', {
      data: {
        ProcessingID: processingId,
        ImageUrl: file.url.replace(CommodityInfoWrite.defaults.baseURL, '')
      }
    })
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchPackMaterialsImages(processingId)
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

// 上传前校验
const beforePackMaterialsUpload = (file: File) => {
  if (!processingInfo.value?.ProcessingID) {
    ElMessage.error('请先保存深加工信息');
    return false;
  }
  if (packMaterialsImages.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
}

// 上传成功回调（可选，主要用于el-upload的on-success）
const handlePackMaterialsUploadSuccess = () => {
  // 实际刷新已在customPackMaterialsUpload里做了
}

const processingEnterpriseInfo = ref<any>(null);
const processingId = ref<number>(1); // 实际应从props或父组件获取

async function fetchProcessingEnterpriseInfo(processingId) {
  if (!processingId) { processingEnterpriseInfo.value = null; return; }
  const res = await CommodityInfoRead.get('/api/Processing/GetProcessingEnterpriseInfoByProcessingId', {
    params: { ProcessingID: processingId }
  });
  if (res.data && res.data.code === 200 && res.data.data) {
    processingEnterpriseInfo.value = res.data.data;
  } else {
    processingEnterpriseInfo.value = null;
  }
}

// 3. 监听processingInfo.value?.ProcessingID变化自动查企业信息
watch(() => processingInfo.value?.ProcessingID, (id) => {
  if (id) fetchProcessingEnterpriseInfo(id)
}, { immediate: true })

// 1. 弹窗相关变量
const processingEnterpriseDialogVisible = ref(false)
const processingEnterpriseForm = reactive({
  Processing_enterpriseInfoId: 0,
  ProcessingID: 0,
  Company_Name: '',
  Production_license: '',
  Photoof_processing_enterprises: '',
  IsDelete: false
})

// 2. 打开弹窗，判断有无数据，反填或清空
function openProcessingEnterpriseDialog() {
  if (processingEnterpriseInfo.value) {
    // 有数据，反填
    Object.assign(processingEnterpriseForm, {
      Processing_enterpriseInfoId: processingEnterpriseInfo.value.Processing_enterpriseInfoId,
      ProcessingID: processingEnterpriseInfo.value.ProcessingID,
      Company_Name: processingEnterpriseInfo.value.Company_Name,
      Production_license: processingEnterpriseInfo.value.Production_license,
      Photoof_processing_enterprises: processingEnterpriseInfo.value.Photoof_processing_enterprises,
      IsDelete: processingEnterpriseInfo.value.IsDelete ?? false
    })
  } else {
    // 无数据，清空
    Object.assign(processingEnterpriseForm, {
      Processing_enterpriseInfoId: 0,
      ProcessingID: processingInfo.value?.ProcessingID || 0,
      Company_Name: '',
      Production_license: '',
      Photoof_processing_enterprises: '',
      IsDelete: false
    })
  }
  processingEnterpriseDialogVisible.value = true
}

// 3. 保存操作，自动判断新增或修改
async function handleSaveProcessingEnterprise() {
  let res
  if (processingEnterpriseInfo.value) {
    // 修改
    res = await CommodityInfoWrite.put('/api/Processing/UpdateProcessingEnterpriseInfo', processingEnterpriseForm)
  } else {
    // 新增
    res = await CommodityInfoWrite.post('/api/Processing/AddProcessingEnterpriseInfo', {
      ProcessingID: processingEnterpriseForm.ProcessingID,
      Company_Name: processingEnterpriseForm.Company_Name,
      Production_license: processingEnterpriseForm.Production_license,
      Photoof_processing_enterprises: processingEnterpriseForm.Photoof_processing_enterprises
    })
  }
  if (res.data && res.data.code === 200) {
    ElMessage.success('保存成功')
    processingEnterpriseDialogVisible.value = false
    // 保存后刷新企业信息
    fetchProcessingEnterpriseInfo(processingEnterpriseForm.ProcessingID)
  } else {
    ElMessage.error(res.data.msg || '保存失败')
  }
}

const processingEnterprisePhotoFileList = ref<any[]>([]);
const processingEnterprisePhotoUploadAction = CommodityInfoWrite.defaults.baseURL + '/api/Picture/UploadProcessingEnterprisePhotoImages';

// 回显：根据processingEnterpriseInfo.Photoof_processing_enterprises回显图片
watch(() => processingEnterpriseInfo.value?.Photoof_processing_enterprises, (val) => {
  if (val) {
    processingEnterprisePhotoFileList.value = val.split(',').filter((url: string) => url && url !== 'string').map((url: string, idx: number) => ({
      name: `图片${idx + 1}`,
      url: url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url,
      status: 'done',
      rawUrl: url
    }));
  } else {
    processingEnterprisePhotoFileList.value = [];
  }
}, { immediate: true });

const beforeProcessingEnterprisePhotoUpload = (file: File) => {
  if (!processingEnterpriseInfo.value?.Processing_enterpriseInfoId) {
    ElMessage.error('请先保存企业信息');
    return false;
  }
  if (processingEnterprisePhotoFileList.value.length >= 9) {
    ElMessage.warning('最多上传9张图片');
    return false;
  }
  return true;
};

const handleProcessingEnterprisePhotoUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response && response.code === 200) {
    ElMessage.success('上传成功');
    // 重新查企业信息，自动刷新图片
    fetchProcessingEnterpriseInfo(processingEnterpriseInfo.value.ProcessingID);
  } else {
    ElMessage.error(response?.msg || '上传失败');
  }
};

const handleProcessingEnterprisePhotoRemove = async (file: any, fileList: any[]) => {
  if (!processingEnterpriseInfo.value?.Processing_enterpriseInfoId || !file.rawUrl) return;
  try {
    const res = await CommodityInfoWrite.delete('/api/Picture/DeleteProcessingEnterprisePhotoImage', {
      data: {
        Processing_enterpriseInfoId: processingEnterpriseInfo.value.Processing_enterpriseInfoId,
        ImageUrl: file.rawUrl
      }
    });
    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功');
      fetchProcessingEnterpriseInfo(processingEnterpriseInfo.value.ProcessingID);
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch {
    ElMessage.error('删除失败');
  }
};

function getFullImageUrl(url: string) {
  if (!url) return ''
  // 如果是http开头但host不是baseURL，强制替换为baseURL
  if (url.startsWith('http') && !url.startsWith(CommodityInfoWrite.defaults.baseURL)) {
    const idx = url.indexOf('/Img/')
    if (idx !== -1) {
      url = url.substring(idx)
    }
    return CommodityInfoWrite.defaults.baseURL + url
  }
  return url.startsWith('http') ? url : CommodityInfoWrite.defaults.baseURL + url
}

</script>

<style scoped>
.details-container {
  padding: 20px;
  background-color: #f4f6f9;
  height: 100%;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.main-info-card {
  margin-bottom: 32px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 32px 32px 24px 32px;
}

.main-info-flex {
  display: flex;
  gap: 40px;
}

.main-info-actions {
  margin-top: 24px;
}

.report-section {
  margin-top: 32px;
}

.tab-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 24px;
}

.product-image {
  flex-shrink: 0;
}

.product-info {
  flex-grow: 1;
}

.product-name {
  font-size: 28px;
  font-weight: bold;
  margin-top: 0;
  margin-bottom: 25px;
}

.info-grid {
  margin-bottom: 20px;
}

.info-item {
  font-size: 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: 500;
  color: #606266;
  margin-right: 15px;
  min-width: 110px;
}

.value {
  color: #303133;
}

.report-images {
  display: flex;
  gap: 10px;
}

.aquaculture-card {
  margin-top: 0;
  background: #fff;
  border-radius: 10px;
  box-shadow: none;
  padding: 0;
}

.healthcare-section {
  margin-top: 24px;
}

.section-title-blue {
  font-size: 20px;
  font-weight: bold;
  color: #1976d2;
  margin-right: 16px;
  display: inline-block;
}

.enterprise-info-container {
  margin: 24px 0;
}

.enterprise-info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.enterprise-info-label {
  color: #666;
  margin-right: 8px;
  min-width: 80px;
  font-weight: bold;
}

.enterprise-photo-section {
  margin: 24px 0;
}

.custom-upload-card {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.custom-upload-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.custom-upload-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  border-radius: 6px;
}

.custom-upload-card:hover .custom-upload-mask {
  opacity: 1;
}

.custom-upload-action {
  color: #fff;
  font-size: 28px;
  margin: 0 8px;
  cursor: pointer;
}

/* 供应商信息样式 */
.supplier-block {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px 24px 16px 24px;
  margin-bottom: 24px;
  background: #fff;
}
.supplier-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.supplier-type-bar {
  width: 4px;
  height: 20px;
  background: #1976d2;
  border-radius: 2px;
  margin-right: 8px;
  display: inline-block;
}
.supplier-batch {
  font-size: 15px;
  margin-bottom: 8px;
}
.supplier-label {
  color: #666;
  margin-bottom: 4px;
}
.supplier-materials {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
  align-items: center;
}
</style>